import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';

dayjs.extend(utc);

// 判断是否是特殊时区
function isSpecialTimezone(timezone = '') {
	return (
		timezone === '(UTC) 协调世界时' ||
		timezone === '(UTC+00:00) 卡萨布兰卡' ||
		timezone === '(UTC+00:00) 蒙罗维亚，雷克雅未克'
	);
}

// 获取时区标记
export function getUTCStr(UTC = '') {
	const timezone = UTC;
	if (isSpecialTimezone(timezone)) return 'UTC';
	if (String(timezone).indexOf('UTC') === -1) return '';
	const strList = timezone.match(/UTC([+|-])(\d+):(\d+)/);
	return strList?.[0];
}

export function getUTCOffset(UTC = '') {
	const timezone = UTC;
	if (isSpecialTimezone(timezone) || String(timezone).indexOf('UTC') === -1) return 0;
	const strList = timezone.match(/UTC([+|-])(\d+):(\d+)/) || '';
	const num =
		(parseInt(strList[1], 10) + (parseInt(strList[2], 10) * 60 + parseInt(strList[3], 10))) * 60000;
	return num;
}

// 当前时区时间戳 -> 当前时区时间格式
export function transDate(timestamp: string, tag = 0) {
	const offset = getUTCOffset() - 0;
	const tstap = Number(timestamp);
	if (tag === 1) {
		return dayjs.utc(tstap + offset).format('YYYY-MM-DD HH:mm:ss');
	}
	return dayjs.utc(tstap + offset).format('YYYY-MM-DD');
}

// 将json串中的时间格式转时间戳YYYY-MM-dd HH:mm:ss
export function matchTimestampToFormat(str: string) {
	return (
		str?.replace(/"\d{13}"/gi, (match) => {
			match = match.replaceAll('"', '');
			return `"${transDate(match, 1)}"`;
		}) || '{}'
	);
}
// 当前时区时间格式 -> 当前时区时间戳
export function zoneStrToZoneTimestamp(str: string) {
	const utcStr = getUTCStr();
	const date = dayjs(`${str} ${utcStr}`);
	return date.valueOf();
}

// 将json串中的时间戳转成时间格式YYYY-MM-dd HH:mm:ss
export function matchFormatToTimestamp(str: string) {
	return (
		str?.replace(/"\d{4}-\d{2}-\d{2}(\s\d{2}:\d{2}:\d{2})?"/gi, (match) => {
			match = match.replaceAll('"', '');
			return `"${zoneStrToZoneTimestamp(match)}"`;
		}) || '{}'
	);
}
